$ErrorActionPreference = "Stop"

param(
    [string]$EsHost = "http://localhost:9200",
    [string]$AppHost = "http://localhost:8080"
)

Write-Host "=== Elasticsearch 商品搜索自动验证脚本 ===" -ForegroundColor Cyan
Write-Host "ES地址: $EsHost" -ForegroundColor Yellow
Write-Host "应用地址: $AppHost" -ForegroundColor Yellow
Write-Host ""

# 1. 检查 ES 是否运行
Write-Host "1. 检查 Elasticsearch 连接..." -ForegroundColor Green
try {
    $esInfo = Invoke-RestMethod -Uri $EsHost -TimeoutSec 5
    Write-Host "✓ ES 运行正常，版本: $($esInfo.version.number)" -ForegroundColor Green
} catch {
    Write-Host "✗ ES 连接失败: $_" -ForegroundColor Red
    exit 1
}

# 2. 检查应用是否运行
Write-Host "2. 检查应用连接..." -ForegroundColor Green
try {
    $pingResult = Invoke-RestMethod -Uri "$AppHost/api/products/ping" -TimeoutSec 5
    Write-Host "✓ 应用运行正常" -ForegroundColor Green
} catch {
    Write-Host "✗ 应用连接失败: $_" -ForegroundColor Red
    Write-Host "请先启动应用: mvn spring-boot:run" -ForegroundColor Yellow
    exit 1
}

# 3. 等待索引和数据加载
Write-Host "3. 等待数据加载..." -ForegroundColor Green
Start-Sleep -Seconds 3

# 4. 验证索引是否存在
Write-Host "4. 检查索引状态..." -ForegroundColor Green
try {
    $indexInfo = Invoke-RestMethod -Uri "$EsHost/products" -TimeoutSec 5
    Write-Host "✓ products 索引存在" -ForegroundColor Green
} catch {
    Write-Host "✗ products 索引不存在" -ForegroundColor Red
    exit 1
}

# 5. 检查数据数量
Write-Host "5. 检查数据数量..." -ForegroundColor Green
try {
    $countResult = Invoke-RestMethod -Uri "$EsHost/products/_count" -TimeoutSec 5
    $docCount = $countResult.count
    Write-Host "✓ 索引中有 $docCount 条数据" -ForegroundColor Green
    if ($docCount -eq 0) {
        Write-Host "✗ 没有数据，请检查数据加载" -ForegroundColor Red
        exit 1
    }
} catch {
    Write-Host "✗ 获取数据数量失败: $_" -ForegroundColor Red
    exit 1
}

# 6. 执行搜索测试
Write-Host "6. 执行搜索测试..." -ForegroundColor Green
$testQueries = @(
    @{query="iphone"; expect="iPhone"},
    @{query="nike"; expect="Nike"},
    @{query="apple"; expect="Apple"},
    @{query="phone"; expect="phone"},
    @{query="laptop"; expect="laptop"},
    @{query="black"; expect="black"},
    @{query="ipho"; expect="iPhone"},  # 部分匹配测试
    @{query="nkie"; expect="Nike"},    # 模糊匹配测试
    @{query="macbok"; expect="MacBook"} # 拼写错误测试
)

$successCount = 0
$totalTests = $testQueries.Count

foreach ($test in $testQueries) {
    $query = $test.query
    $expect = $test.expect

    try {
        $searchUrl = "$AppHost/api/products/search?q=$([System.Web.HttpUtility]::UrlEncode($query))"
        $results = Invoke-RestMethod -Uri $searchUrl -TimeoutSec 10

        if ($results.Count -gt 0) {
            $found = $false
            foreach ($result in $results) {
                $resultText = "$($result.name) $($result.category) $($result.color) $($result.attributes.brand)"
                if ($resultText -match $expect) {
                    $found = $true
                    break
                }
            }

            if ($found) {
                Write-Host "  ✓ '$query' -> 找到 $($results.Count) 条结果，包含 '$expect'" -ForegroundColor Green
                $successCount++
            } else {
                Write-Host "  ✗ '$query' -> 找到 $($results.Count) 条结果，但不包含 '$expect'" -ForegroundColor Yellow
            }
        } else {
            Write-Host "  ✗ '$query' -> 没有找到结果" -ForegroundColor Red
        }
    } catch {
        Write-Host "  ✗ '$query' -> 搜索失败: $_" -ForegroundColor Red
    }
}

# 7. 输出测试结果
Write-Host ""
Write-Host "=== 测试结果汇总 ===" -ForegroundColor Cyan
Write-Host "成功: $successCount / $totalTests" -ForegroundColor $(if ($successCount -eq $totalTests) { "Green" } else { "Yellow" })

if ($successCount -eq $totalTests) {
    Write-Host "🎉 所有测试通过！多字段模糊搜索功能正常工作" -ForegroundColor Green
} elseif ($successCount -gt ($totalTests * 0.7)) {
    Write-Host "⚠️  大部分测试通过，功能基本正常" -ForegroundColor Yellow
} else {
    Write-Host "❌ 多数测试失败，请检查配置" -ForegroundColor Red
}

# 8. 性能测试
Write-Host ""
Write-Host "8. 性能测试..." -ForegroundColor Green
$perfQueries = @("iphone", "nike", "laptop")
$totalTime = 0

foreach ($query in $perfQueries) {
    $startTime = Get-Date
    try {
        $searchUrl = "$AppHost/api/products/search?q=$([System.Web.HttpUtility]::UrlEncode($query))"
        $results = Invoke-RestMethod -Uri $searchUrl -TimeoutSec 10
        $endTime = Get-Date
        $duration = ($endTime - $startTime).TotalMilliseconds
        $totalTime += $duration
        Write-Host "  '$query' 响应时间: $([math]::Round($duration, 2))ms" -ForegroundColor Cyan
    } catch {
        Write-Host "  '$query' 性能测试失败: $_" -ForegroundColor Red
    }
}

$avgTime = $totalTime / $perfQueries.Count
Write-Host "平均响应时间: $([math]::Round($avgTime, 2))ms" -ForegroundColor Cyan

Write-Host ""
Write-Host "验证完成！可以访问 $AppHost 查看前端界面" -ForegroundColor Green
